<template>
  <div class="ai-training-annotation">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <!-- <h1 class="page-title">🤖 AI训练数据标注中心</h1> -->
      <el-button type="primary" @click="handleAddSample">
        新增训练样本
      </el-button>
    </div>

    <!-- 训练状态概览 -->
    <el-card
      class="stats-card"
      :body-style="{ padding: '15px' }"
      v-loading="statsLoading"
    >
      <h2 class="section-title">📊 训练状态概览</h2>
      <div class="stats-container">
        <StatisticCard
          label="训练样本总数"
          :value="formatNumber(statistics.totalSamples)"
          type="primary"
        />
        <StatisticCard
          label="本周新增"
          :value="`+${statistics.weeklyAdded}`"
          type="success"
        />
        <StatisticCard
          label="AI准确率"
          :value="`${statistics.accuracy}%`"
          type="warning"
        />
        <StatisticCard
          label="模型版本"
          :value="statistics.modelVersion"
          type="info"
        />
      </div>
    </el-card>

    <!-- 步骤导航 -->
    <el-steps v-model="currentStep" class="steps-navigation">
      <el-step title="资产基本信息" />
      <el-step title="部门标注(核心)" />
      <el-step title="提交完成" />
    </el-steps>

    <!-- 步骤内容区域 -->
    <div class="steps-content">
      <!-- 第1步: 资产基本信息 -->
      <el-card
        v-if="currentStep === 0"
        class="step-card"
        :body-style="{ padding: '20px' }"
      >
        <h2 class="step-title">第1步: 资产基本信息</h2>

        <el-card class="form-section" :body-style="{ padding: '15px' }">
          <h3 class="section-title">📍 资产识别</h3>

          <el-form-item label="IP地址" class="form-item" :help="ipHelperText">
            <el-input
              v-model="assetForm.ipAddress"
              placeholder="请输入IP地址"
              :maxlength="50"
            />
          </el-form-item>

          <el-form-item label="端口号" class="form-item">
            <el-input
              v-model="assetForm.port"
              placeholder="请输入端口号"
              type="number"
              :maxlength="5"
            />
          </el-form-item>

          <el-form-item label="资产标题" class="form-item">
            <el-input
              v-model="assetForm.title"
              placeholder="请输入资产标题"
              :maxlength="100"
            />
          </el-form-item>
        </el-card>

        <el-card
          class="form-section"
          :body-style="{ padding: '15px' }"
          style="margin-top: 15px"
        >
          <div
            class="expandable-section-header"
            @click="toggleExpandableSection"
          >
            <h3 class="section-title">🔍 扩展特征 (可选,帮助AI更准确识别)</h3>
            <el-button
              type="text"
              size="small"
              @click.stop="toggleExpandableSection"
            >
              {{ isExpandableOpen ? "收起" : "展开" }}
            </el-button>
          </div>

          <div v-if="isExpandableOpen" class="expandable-content">
            <p class="hint-text">
              💡 提示: 外网资产自动提取,内网资产建议手动填写以提高识别准确率
            </p>

            <el-form-item label="服务类型" class="form-item">
              <el-input
                v-model="assetForm.serviceType"
                placeholder="如: nginx, apache, tomcat, mysql"
                :maxlength="100"
              />
            </el-form-item>

            <el-form-item label="中间件/产品" class="form-item">
              <el-input
                v-model="assetForm.middleware"
                placeholder="如: Nginx 1.18, PHP 7.4"
                :maxlength="100"
              />
            </el-form-item>

            <el-form-item label="域名/URL" class="form-item">
              <el-input
                v-model="assetForm.domain"
                placeholder="如: monitor.example.com"
                :maxlength="200"
              />
            </el-form-item>

            <el-form-item label="关键特征词" class="form-item">
              <el-input
                v-model="assetForm.keywords"
                placeholder="如: 监控平台, 管理后台, OA系统"
                :maxlength="200"
              />
            </el-form-item>

            <el-form-item label="Banner信息" class="form-item">
              <el-input
                v-model="assetForm.banner"
                type="textarea"
                :rows="2"
                placeholder="服务响应头"
              />
            </el-form-item>

            <el-form-item label="备注说明" class="form-item">
              <el-input
                v-model="assetForm.remarks"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </div>
        </el-card>

        <div class="step-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="goToNextStep"> 下一步 → </el-button>
        </div>
      </el-card>

      <!-- 第2步: 部门标注(核心) -->
      <el-card
        v-if="currentStep === 1"
        class="step-card"
        :body-style="{ padding: '20px' }"
      >
        <h2 class="step-title">第2步: 部门标注 (AI训练标签)</h2>

        <el-card class="form-section" :body-style="{ padding: '15px' }">
          <h3 class="section-title">
            🏢 确认部门归属 * (必填,最重要的标注信息)
          </h3>

          <el-form-item class="form-item">
            <el-select
              v-model="annotationForm.department"
              placeholder="请选择或输入部门"
              filterable
              allow-create
              default-first-option
              style="width: 100%"
            >
              <el-option
                v-for="dept in departmentOptions"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </el-form-item>

          <p class="hint-text">💡 这是AI训练的核心标签,请认真选择!</p>

          <div class="ai-recommendations" v-loading="recommendationsLoading">
            <p class="recommendation-title">✅ AI推荐 (基于规则引擎预判):</p>
            <div v-if="recommendations.length === 0" class="no-recommendations">
              <p class="hint-text">暂无推荐，请手动选择部门</p>
            </div>
            <div
              v-for="(rec, index) in recommendations"
              :key="index"
              class="recommendation-item"
            >
              <span class="rank">{{ getRankEmoji(rec.rank) }}</span>
              <span class="dept-name">{{ rec.department }}</span>
              <span class="confidence">({{ rec.confidence }}%)</span>
              <el-button
                type="text"
                size="small"
                @click="selectRecommendedDept(rec.department)"
              >
                一键选择
              </el-button>
            </div>
          </div>
        </el-card>

        <el-card
          class="form-section"
          :body-style="{ padding: '15px' }"
          style="margin-top: 15px"
        >
          <h3 class="section-title">🏷️ 样本类型 *</h3>

          <el-radio-group v-model="annotationForm.sampleType">
            <el-radio label="positive">正样本 (该资产属于选定部门)</el-radio>
            <el-radio label="negative">负样本 (该资产不属于选定部门)</el-radio>
          </el-radio-group>
        </el-card>

        <el-card
          class="form-section"
          :body-style="{ padding: '15px' }"
          style="margin-top: 15px"
        >
          <h3 class="section-title">📊 置信度 (可选)</h3>

          <el-radio-group v-model="annotationForm.confidence">
            <el-radio :label="100">非常确定(100%)</el-radio>
            <el-radio :label="80">比较确定(80%)</el-radio>
            <el-radio :label="60">一般(60%)</el-radio>
            <el-radio :label="40">不确定(40%)</el-radio>
          </el-radio-group>
        </el-card>

        <div class="step-actions">
          <el-button @click="goToPrevStep">← 上一步</el-button>
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            type="primary"
            @click="submitAnnotation"
            :loading="submitting"
          >
            ✅ 提交标注
          </el-button>
        </div>
      </el-card>

      <!-- 第3步: 提交成功反馈 -->
      <el-card
        v-if="currentStep === 2"
        class="step-card success-card"
        :body-style="{ padding: '20px' }"
      >
        <div class="success-header">
          <i class="el-icon-success success-icon"></i>
          <h2 class="step-title">🎉 训练样本标注成功!</h2>
        </div>

        <div class="model-training-status">
          <p class="training-text">🤖 AI模型自动学习中...</p>
          <el-progress
            :percentage="Number(trainingProgress)"
            :stroke-width="8"
            style="margin: 20px 0"
          />

          <div class="training-steps">
            <div class="training-step">✓ 特征提取完成</div>
            <div class="training-step">✓ 权重更新完成</div>
            <div class="training-step">✓ 模型验证完成</div>
          </div>
        </div>

        <div class="result-stats">
          <h3 class="section-title">📊 更新结果:</h3>
          <ul class="stats-list">
            <li>
              • 训练样本总数:
              {{ formatNumber(statistics.totalSamples + 1) }} (+1)
            </li>
            <li>
              • 模型准确率:
              {{ (parseFloat(statistics.accuracy) + 0.02).toFixed(2) }}%
              (+0.02%)
            </li>
            <li>• 下次全量训练: 今晚23:00</li>
          </ul>
        </div>

        <div class="success-actions">
          <el-button @click="resetAndAddAnother"> 继续标注 </el-button>
          <el-button type="primary" @click="goToAssetList">
            返回列表
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import StatisticCard from "./components/StatisticCard.vue";
import {
  getTrainingStats,
  getRecommendedDepartments,
  submitTrainingLabel,
} from "../../servers";

// 页面状态
const currentStep = ref(0);
const isExpandableOpen = ref(false);
const submitting = ref(false);
const trainingProgress = ref(0);
const statsLoading = ref(false);
const recommendationsLoading = ref(false);

// 统计数据
const statistics = reactive({
  totalSamples: 0,
  weeklyAdded: 0,
  accuracy: "0",
  modelVersion: "v0.0.0",
});

// 推荐部门列表
const recommendations = ref<
  Array<{
    rank: number;
    department: string;
    confidence: number;
    match_reasons?: string[];
  }>
>([]);

// 部门选项（从推荐中获取，如果没有推荐则使用默认列表）
const departmentOptions = computed(() => {
  const deptSet = new Set<string>();
  // 添加推荐部门
  recommendations.value.forEach((rec) => {
    deptSet.add(rec.department);
  });
  // 如果当前选择的部门不在推荐中，也添加进去
  if (annotationForm.department) {
    deptSet.add(annotationForm.department);
  }
  return Array.from(deptSet).map((dept) => ({
    label: dept,
    value: dept,
  }));
});

// 资产表单数据
const assetForm = reactive({
  ipAddress: "",
  port: "",
  title: "",
  serviceType: "",
  middleware: "",
  domain: "",
  keywords: "",
  banner: "",
  remarks: "",
});

// 标注表单数据
const annotationForm = reactive({
  department: "",
  sampleType: "positive" as "positive" | "negative",
  confidence: 80,
});

// 格式化数字显示（添加千位分隔符）
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// IP地址帮助文本
const ipHelperText = "仅探测互联网暴露面,内网IP可选填";

// 切换扩展特征区域的显示/隐藏
const toggleExpandableSection = () => {
  isExpandableOpen.value = !isExpandableOpen.value;
};

// 获取训练统计
const fetchTrainingStats = async () => {
  statsLoading.value = true;
  try {
    const { data } = await getTrainingStats();
    if (data) {
      statistics.totalSamples = data.total_samples?.value || 0;
      statistics.weeklyAdded = data.weekly_added?.value || 0;
      statistics.accuracy = (data.model_accuracy?.value || 0).toFixed(1);
      statistics.modelVersion = data.model_version?.version || "v0.0.0";
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取训练统计失败");
  } finally {
    statsLoading.value = false;
  }
};

// 获取推荐部门
const fetchRecommendations = async () => {
  if (!assetForm.ipAddress && !assetForm.title) {
    recommendations.value = [];
    return;
  }

  recommendationsLoading.value = true;
  try {
    const { data } = await getRecommendedDepartments({
      ip: assetForm.ipAddress || undefined,
      port: assetForm.port ? Number(assetForm.port) : undefined,
      title: assetForm.title || undefined,
    });

    if (data?.recommendations) {
      recommendations.value = data.recommendations;
    } else {
      recommendations.value = [];
    }
  } catch (error: any) {
    ElMessage.warning(error?.message || "获取推荐部门失败，请手动选择");
    recommendations.value = [];
  } finally {
    recommendationsLoading.value = false;
  }
};

// 获取排名图标
const getRankEmoji = (rank: number) => {
  const emojiMap: Record<number, string> = {
    1: "🥇",
    2: "🥈",
    3: "🥉",
  };
  return emojiMap[rank] || `${rank}.`;
};

// 步骤导航
const goToNextStep = async () => {
  // 简单验证
  if (!assetForm.title && !assetForm.ipAddress) {
    ElMessage.warning("请至少填写IP地址或资产标题");
    return;
  }

  // 进入第二步时获取推荐部门
  if (currentStep.value === 0) {
    await fetchRecommendations();
  }

  currentStep.value++;
};

const goToPrevStep = () => {
  currentStep.value--;
};

// 选择推荐的部门
const selectRecommendedDept = (dept: string) => {
  annotationForm.department = dept;
};

// 提交标注
const submitAnnotation = async () => {
  // 验证
  if (!annotationForm.department) {
    ElMessage.warning("请选择部门归属");
    return;
  }

  submitting.value = true;

  try {
    // 构建提交数据
    const submitData: any = {
      department_label: annotationForm.department,
      sample_type: annotationForm.sampleType,
    };

    // 可选基础字段
    if (assetForm.ipAddress) {
      submitData.ip = assetForm.ipAddress;
    }
    if (assetForm.port) {
      submitData.port = Number(assetForm.port);
    }
    if (annotationForm.confidence) {
      submitData.confidence = annotationForm.confidence;
    }

    // 可选扩展特征字段
    if (assetForm.title) {
      submitData.title = assetForm.title;
    }
    if (assetForm.serviceType) {
      submitData.service_type = assetForm.serviceType;
    }
    if (assetForm.middleware) {
      submitData.middleware_info = assetForm.middleware;
    }
    if (assetForm.domain) {
      submitData.domain_name = assetForm.domain;
    }
    if (assetForm.keywords) {
      submitData.keywords = assetForm.keywords;
    }
    if (assetForm.banner) {
      submitData.banner_info = assetForm.banner;
    }
    if (assetForm.remarks) {
      submitData.note = assetForm.remarks;
    }

    const { data } = await submitTrainingLabel(submitData);

    if (data) {
      ElMessage.success("训练样本标注成功，AI模型已更新");

      // 更新统计（增加1个样本）
      statistics.totalSamples += 1;
      statistics.weeklyAdded += 1;

      // 进入成功页面
      currentStep.value++;

      // 模拟训练进度动画
      let progress = 0;
      const interval = setInterval(() => {
        progress += 10;
        trainingProgress.value = progress;
        if (progress >= 100) {
          clearInterval(interval);
        }
      }, 300);
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "提交失败，请重试");
  } finally {
    submitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  if (confirm("确定要取消当前标注吗？已填写的内容将不会保存。")) {
    // 实际项目中这里可能需要跳转到列表页
    ElMessage.info("已取消标注");
  }
};

// 新增训练样本
const handleAddSample = () => {
  resetForm();
  currentStep.value = 0;
};

// 重置表单
const resetForm = () => {
  // 重置表单数据
  Object.assign(assetForm, {
    ipAddress: "",
    port: "",
    title: "",
    serviceType: "",
    middleware: "",
    domain: "",
    keywords: "",
    banner: "",
    remarks: "",
  });

  Object.assign(annotationForm, {
    department: "",
    sampleType: "positive" as "positive" | "negative",
    confidence: 80,
  });

  trainingProgress.value = 0;
  isExpandableOpen.value = false;
};

// 继续标注
const resetAndAddAnother = () => {
  resetForm();
  currentStep.value = 0;
};

// 返回列表
const goToAssetList = () => {
  // 跳转到疑似资产列表页
  window.location.href = "/taskmg/suspectedAssets";
};

// 监听资产表单变化，自动获取推荐（可选，也可以只在进入第二步时获取）
watch(
  () => [assetForm.ipAddress, assetForm.port, assetForm.title],
  () => {
    // 如果已经在第二步，自动刷新推荐
    if (currentStep.value === 1) {
      fetchRecommendations();
    }
  }
);

// 页面加载时
onMounted(async () => {
  // 默认展开扩展特征
  isExpandableOpen.value = true;
  // 获取训练统计
  await fetchTrainingStats();
});
</script>

<style scoped lang="scss">
.ai-training-annotation {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .stats-card {
    margin-bottom: 20px;
    border-radius: 8px;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .steps-navigation {
    margin-bottom: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 8px;
    padding-left: 20px;
  }

  .step-card {
    margin-bottom: 20px;
    border-radius: 8px;
  }

  .step-title {
    font-size: 18px;
    font-weight: 500;
    margin: 0 0 20px 0;
    color: #333;
  }

  .form-section {
    border-radius: 6px;
    margin-bottom: 10px;
  }

  .form-item {
    margin-bottom: 15px;
  }

  .expandable-section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .expandable-content {
    padding-top: 10px;
  }

  .hint-text {
    color: #666;
    font-size: 13px;
    margin: 0 0 15px 0;
    padding: 5px 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    display: inline-block;
  }

  .step-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }

  .ai-recommendations {
    margin-top: 15px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 6px;
  }

  .recommendation-title {
    font-weight: 500;
    margin-bottom: 10px;
    color: #333;
  }

  .recommendation-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px dashed #eee;

    &:last-child {
      border-bottom: none;
    }
  }

  .rank {
    width: 30px;
    display: inline-block;
  }

  .dept-name {
    flex: 1;
    margin: 0 10px;
  }

  .confidence {
    color: #666;
    font-size: 13px;
    margin-right: 10px;
  }

  .success-card {
    text-align: center;
    border-color: #e1f5e1;
  }

  .success-header {
    margin-bottom: 20px;
  }

  .success-icon {
    font-size: 48px;
    color: #52c41a;
    margin-bottom: 10px;
  }

  .model-training-status {
    margin-bottom: 20px;
  }

  .training-text {
    font-size: 16px;
    margin-bottom: 10px;
    color: #333;
  }

  .training-steps {
    text-align: left;
    margin-top: 15px;
  }

  .training-step {
    margin: 5px 0;
    color: #666;
  }

  .result-stats {
    text-align: left;
    background-color: #f9fafb;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 20px;
  }

  .stats-list {
    padding-left: 20px;
    margin: 10px 0 0 0;

    li {
      margin: 5px 0;
      color: #333;
    }
  }

  .success-actions {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
  }
}
</style>
